package concurrent;

import java.util.Random;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TransferQueue;

/**
 * @author Summerday
 */
public class TestTransferQueue {

    // 无锁算法 无界队列
    static TransferQueue<Integer> queue = new LinkedTransferQueue<>();

    public static void main (String[] args) throws InterruptedException {
        queue.put(1);

        //for (int i = 1; i <= 10; i++) {
        //    new Thread(() -> {
        //        try {
        //            System.out.println(Thread.currentThread().getName() + "消费 id - " + queue.take());
        //            System.out.println("---------------------------------------------");
        //        } catch (InterruptedException e) {
        //            e.printStackTrace();
        //        }
        //    }, "consumer" + i).start();
        //}
        //
        //Thread producer = new Thread(() -> {
        //    while (true) {
        //        System.out.println("当前队列中等待的线程" + queue.getWaitingConsumerCount());
        //        // 如果队列中有等待的消费者
        //        if (queue.hasWaitingConsumer()) {
        //            int product = new Random().nextInt(500);
        //            try {
        //                System.out.println(Thread.currentThread().getName() + "生产 id - " + product);
        //                queue.tryTransfer(product);
        //                TimeUnit.MILLISECONDS.sleep(100); // 等待消费
        //            } catch (InterruptedException e) {
        //                e.printStackTrace();
        //            }
        //        }
        //    }
        //}, "producer");
        //producer.setDaemon(true);
        //producer.start();

        /**
 Starting at head, skip already-matched nodes until finding
 an unmatched node of opposite mode, if one exists, in which
 case matching it and returning, also if necessary updating
 head to one past the matched node (or the node itself if the
 list has no other unmatched nodes). If the CAS misses, then
 a loop retries advancing head by two steps until either
 success or the slack is at most two. By requiring that each
 attempt advances head by two (if applicable), we ensure that
 the slack does not grow without bound. Traversals also check
 if the initial head is now off-list, in which case they
 start at the new head.

 If no candidates are found and the call was untimed
 poll/offer, (argument "how" is NOW) return.
         */
    }
}


